package com.xuzhiguang.lightnat.server.core.server.proxy.handler;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.transfer.DisconnectPush;
import com.xuzhiguang.lightnat.server.core.server.transfer.TransferChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class InactiveHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        // 是否同步 disconnect 到 client
        Boolean syncDisconnect = ProxyChannelManager.getSyncDisconnect(ctx.channel());

        log.debug("proxy channel inactive. channel:{}, syncDisconnect:{}", ctx.channel(), syncDisconnect);

        if (syncDisconnect == null || syncDisconnect) {
            Long transferId = ProxyChannelManager.getTransferId(ctx.channel());
            if (transferId != null) {
                Channel transferChannel = TransferChannelManager.getChannel(transferId);
                if (transferChannel != null) {

                    // transfer 通知 client 断开连接
                    transferChannel.writeAndFlush(new NatMessage(new DisconnectPush()));
                } else {
                    log.warn("transferChannel is null. transferId:{}", transferId);
                }
            }
        }
        super.channelInactive(ctx);
    }
}
